package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"new/cache"
	"new/models"
	"path/filepath"
	"strings"
)

type NewController struct {
	beego.Controller
}
type Msgs struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Size    int         `json:"size"`
	Count   int64       `json:"count"`
	Sumpage int         `json:"sumpage"`
}

func (c *NewController) Add() {
	file, header, err := c.GetFile("img")
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "请选择要上传的文件",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		res := Msg{
			Code: 0,
			Msg:  "上传文件图片不能超过2MB",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	ext := map[string]bool{
		".png":  true,
		".jpeg": true,
	}
	offset := strings.ToLower(filepath.Ext(header.Filename))
	if ext[offset] == false {
		res := Msg{
			Code: 0,
			Msg:  "文件类型只能是png,jpeg格式",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	title := c.GetString("title")
	address := c.GetString("address")
	order, _ := c.GetInt("order")
	status := c.GetString("status")
	people := c.GetString("people")
	var news models.New
	news.Title = title
	news.Address = address
	news.Img = "http://127.0.0.1:8080/" + path
	news.Order = order
	news.Status = status
	news.People = people
	if title == "" || address == "" || order == 0 || status == "" || people == "" {
		res := Msg{
			Code: 0,
			Msg:  "数据不能为空",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if err := news.Add(); err != nil {
		res := Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	res := Msg{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return
}
func (c *NewController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var news models.New
	var newss []*models.New
	key := "new_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		newss, _ = news.Find()
		jsonData, _ := json.Marshal(newss)
		cache.Rdb.Set(cache.Ctx, key, jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &newss)
	}
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.New{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	err := models.DB.Offset(offset).Limit(size).Find(&newss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	} else {
		res := Msgs{
			Code:    200,
			Msg:     "查询成功",
			Data:    newss,
			Page:    page,
			Size:    size,
			Count:   count,
			Sumpage: sumpage,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
}
func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	var news models.New
	news.ID = uint(id)
	news.Hy()
	if id < 1 {
		res := Msg{
			Code: 0,
			Msg:  "id不存在",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if news.Status == "已发布" {
		res := Msg{
			Code: 0,
			Msg:  "已发布新闻禁止删除",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if err := news.Del(); err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	key := fmt.Sprintf("new_del_%d", news.ID)
	jsonData, _ := json.Marshal(news)
	cache.Rdb.Set(cache.Ctx, key, jsonData, 0)
	res := Msg{
		Code: 200,
		Msg:  "删除成功",
		Data: nil,
	}
	c.Data["json"] = res
	c.ServeJSON()
	return
}
